//	CMessageSystem.cpp

#include "MessageSystem.h"

CMessageSystem* CMessageSystem::GetInstance(void)
{
	static CMessageSystem instance;
	return &instance;
}

void CMessageSystem::InitMessageSystem(MESSAGEPROC pfnMsgProc)
{
	//	Error check to make sure the message proc is valid.
	if (!pfnMsgProc)	return;

	//	Get the Msg Proc
	m_pfnMsgProc = pfnMsgProc;
}

void CMessageSystem::SendMsg(CBaseMessage* pMsg, float fDelay)
{
	//	Make sure the message exists.
	if (!pMsg)	return;

	pMsg->SetDelay(fDelay);
	//	Send the message to the queue for processing later on.
	m_MsgQueue.push_back(pMsg);
}

void CMessageSystem::ProcessMessages(float dt)
{
	//	Error check to make sure we get a message proc.
	if(!m_pfnMsgProc)	return;

	//	go through the entire queue and process the messsages that are waiting.
	list<CBaseMessage *>::iterator itt = m_MsgQueue.begin();
	while(itt != m_MsgQueue.end())
	{
		//Check if time is 0
		if((*itt)->GetDelay() > 0.0f)
		{
			(*itt)->SetDelay((*itt)->GetDelay() - dt);
			++itt;
		}
		else //If so then process message
		{
			m_pfnMsgProc(*itt);		//	Process the first message.
			delete *itt;			//	Delete the message memory.
			itt = m_MsgQueue.erase(itt);		//Remove the message
		}
	}
}

void CMessageSystem::ClearMessages(void)
{
	//	Clear out any messages waititng.
	while(!m_MsgQueue.empty())
	{
		delete m_MsgQueue.back();
		m_MsgQueue.pop_back();
	}
}

void CMessageSystem::ShutdownMessageSystem(void)
{
	//	Clear out any messages waiting.
	ClearMessages();

	//	Clear the function pointer
	m_pfnMsgProc = NULL;
}